<template>
  <view class="page">
    <view class="card">
      <view class="title required">联系人</view>
      <view class="row">
        <input v-model="params.name" placeholder="请输入联系人" />
      </view>
      <view class="title required">性别</view>
      <view class="row">
        <radio-group
          :value="params.sex"
          class="flex"
          @change="activityTypeChange"
        >
          <label class="flex align-center">
            <view>
              <radio
                :value="1"
                :checked="params.sex == 1"
                style="transform: scale(0.7)"
              />
            </view>
            <view>男</view>
          </label>
          <label class="flex align-center margin-left">
            <view>
              <radio
                :value="2"
                :checked="params.sex == 2"
                style="transform: scale(0.7)"
              />
            </view>
            <view>女</view>
          </label>
        </radio-group>
      </view>
      <view class="title required">手机号</view>
      <view class="row">
        <input
          v-model="params.phone"
          type="number"
          placeholder="请输入手机号"
        />
      </view>
      <view class="title required">地址</view>
      <view
        class="row flex justiy-between align-center"
        @tap.stop="onChooseLocation"
      >
        <view class="address">
          <text v-if="$data.areaStr">
            {{ $data.areaStr }}
          </text>
          <text v-else class="text-gray-80">请选择地址</text>
        </view>
        <view class="right">
          <image :src="ImgIconRightGray" />
        </view>
      </view>
      <view class="title required">详细地址(门牌号)</view>
      <view class="row">
        <input
          v-model="params.address"
          :maxlength="100"
          placeholder="请输入详细地址(门牌号)"
        />
      </view>
      <view class="row flex align-center" @tap="onCheckDefault">
        <view class="check_img">
          <image v-if="params.isDefault === 0" :src="ImgCheckUnGray" />
          <image v-else :src="ImgCheckGreen" />
        </view>
        <view class="margin-left-sm text-lg">设置为默认地址</view>
      </view>
    </view>
    <view class="foot foot_box">
      <view class="btn btn_cancel" @tap="back">取消</view>
      <view class="btn btn_save" @tap="onSave">保存</view>
    </view>
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import { onLoad, onShow, onReady } from "@dcloudio/uni-app";
import BasicConfig from "../../../utils/config";
import {
  ImgIconRightGray,
  ImgCheckGreen,
  ImgCheckUnGray,
} from "../../../utils/iconMap";
import { useGetLocationReverseAnalysis } from "../../../hooks/useLocation";
import {
  createAddress,
  editAddress,
  getAddressDetail,
} from "../../../api/Interface/address";
import errorCode from "../../../utils/http/errorCode";
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  areaStr: "", // 选择的省市区字符串
});
const params = reactive({
  userAddressId: null,
  name: "", // 收货人姓名
  phone: "", // 收货人手机号
  province: "", // 省份名称
  city: "", // 市名称
  area: "", // 地区名称
  provinceCode: "", // 省份code编码
  cityCode: "", // 市code编码
  areaCode: "", // 地区code编码
  address: "", // 收货人详细地址
  locationAddress: "", // 定位详细地址
  locationTitle: "", // 定位详细地址标题
  isDefault: 0, // 是否默认地址：0=否，1=是
  lat: "", // 纬度
  lng: "", // 经度
  sex: 1, // 性别 1.男 2.女
});
const init = () => {
  uni.setNavigationBarTitle({
    title: params.userAddressId ? "编辑服务地址" : "新增服务地址",
  });
  // 编辑
  if (params.userAddressId) {
    getInfo();
  }
};
const getInfo = () => {
  getAddressDetail({ userAddressId: params.userAddressId }).then((res) => {
    if (res.code === errorCode.success) {
      Object.keys(res.data).forEach((key) => {
        if (params.hasOwnProperty(key)) {
          params[key] = res.data[key];
        }
      });
      // nextTick(() => {
      //   console.log("params", params);
      //   const list = [params.province, params.city, params.area].filter(
      //     (p) => !!p
      //   );
      //   $data.areaStr = list.join(" ");
      // });
      setTimeout(() => {
        console.log("params", params);
        const list = [params.province, params.city, params.area].filter(
          (p) => !!p
        );
        $data.areaStr = list.join(" ");
      }, 100);
    } else {
      BasicConfig.toast(res.msg);
      setTimeout(() => {
        back();
      }, 1500);
    }
  });
};
const onChooseLocation = () => {
  uni.chooseLocation({
    success: function (res) {
      console.log("chooseLocation", res);
      console.log("位置名称：" + res.name);
      console.log("详细地址：" + res.address);
      console.log("纬度：" + res.latitude);
      console.log("经度：" + res.longitude);
      params.address = res.address || res.name;
      params.locationAddress = res.address;
      params.lat = res.latitude;
      params.lng = res.longitude;
      params.locationTitle = res.name;
      useGetLocationReverseAnalysis({
        lat: res.latitude,
        lng: res.longitude,
      }).then((res) => {
        if (res.errMsg === "request:ok" && res.data.status === 0) {
          const { province, city, district } =
            res.data.result.address_component;
          const { pois } = res.data.result;
          if (pois && pois.length > 0 && !params.locationTitle) {
            params.locationTitle = pois[0].title;
          }
          params.province = province;
          params.city = city;
          params.area = district;
          const list = [params.province, params.city, params.area].filter(
            (p) => !!p
          );
          $data.areaStr = list.join(" ");
          const { adcode } = res.data.result.ad_info; // adcode:230102
          params.provinceCode = adcode.substring(0, 2); // + "0000"; // 省份code编码
          params.cityCode = adcode.substring(0, 4); // + "00"; // 市code编码
          params.areaCode = adcode; // 地区code编码
        }
      });
    },
    fail: (fail) => {
      console.log("地址定位失败", fail);
      const { errMsg } = fail;
      if (errMsg === "chooseLocation:fail cancel") {
        console.log("用户取消定位");
        return;
      } else if (errMsg === "chooseLocation:fail system auth deny") {
        uni.showModal({
          content: "定位失败，请确认手机已打开定位",
          showCancel: false,
          confirmText: "知道了",
          confirmColor: BasicConfig.MainColor,
          success: (success) => {},
        });
      } else if (errMsg === "chooseLocation:fail auth deny") {
        uni.showModal({
          content: "定位失败，请确认已设置小程序定位授权",
          cancelText: "取消",
          confirmText: "去设置",
          confirmColor: BasicConfig.MainColor,
          success: (success) => {
            if (success.confirm) {
              uni.openSetting({
                success: (res) => {
                  console.log("定位设置", res);
                },
              });
            }
          },
        });
      }
    },
  });
};
const onCheckDefault = () => {
  params.isDefault = +!!!params.isDefault;
};
const activityTypeChange = (e) => {
  params.sex = Number(e.detail.value);
};
const onSave = () => {
  if (!params.name) {
    BasicConfig.toast("请输入联系人姓名");
    return;
  }
  if (params.name.length > 4) {
    BasicConfig.toast("请输入小于4个字的姓名");
    return;
  }
  if (!uni.$u.test.mobile(params.phone)) {
    BasicConfig.toast("请输入合法的手机号");
    return;
  }
  if (!$data.areaStr) {
    BasicConfig.toast("请选择地址");
    return;
  }
  if (!params.address) {
    BasicConfig.toast("请输入详细地址");
    return;
  }
  console.log("地址添加/编辑参数", params);
  uni.showModal({
    content: "确认提交?",
    success: (success) => {
      if (success.confirm) {
        // 编辑
        if (params.userAddressId) {
          editAddress(params).then((res) => {
            BasicConfig.toast(res.msg);
            if (res.code === errorCode.success) {
              setTimeout(() => {
                back();
              }, 1500);
            }
          });
        }
        // 新增
        else {
          createAddress(params).then((res) => {
            BasicConfig.toast(res.msg);
            if (res.code === errorCode.success) {
              setTimeout(() => {
                back();
              }, 1500);
            }
          });
        }
      }
    },
  });
};
const back = () => {
  uni.navigateBack({
    delta: 1,
  });
};
onLoad((options) => {
  params.userAddressId = options.id;
  init();
});
onShow(() => {});
onReady(() => {});
</script>

<style lang="scss" scoped>
.page {
  background: #ffffff;
  width: 100vw;
  min-height: 100vh;
  .row {
    padding: 30rpx 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 30rpx;
    input {
      width: 100%;
    }
    .address {
      width: calc(100% - 50rpx);
    }
    .right {
      width: 16rpx;
      height: 30rpx;
      margin-left: 30rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
    .check_img {
      width: 40rpx;
      height: 40rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }
  .foot_box {
    padding: 30rpx;
    z-index: 9;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn {
      width: 48%;
      // padding: 30rpx;
      border-radius: 100rpx;
      text-align: center;
      font-size: 34rpx;
    }
    .btn_save {
      background: $main-color;
      color: #ffffff;
    }
    .btn_cancel {
      background: #ffffff;
      color: $main-color;
      border: 1px solid $main-color;
    }
  }
}
</style>
